package com.example.demo.strategy.impl;

import com.example.demo.strategy.UploadStrategy;
import com.example.demo.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;

@Service
public abstract class AbstractUploadStrategyImpl implements UploadStrategy {

    @Override
    public String upload(String path, MultipartFile file) {
        try {
            //获得文件MD5值
            String md5 = FileUtils.getMd5(file.getInputStream());
            //获得文件扩展名
            String extName = FileUtils.getExtName(file.getOriginalFilename());
            //新的文件名
            String fileName = md5 + extName;
            //判断该文件是否存在
            if (!exists(path + fileName)) {
                //不存在继续上传
                uploadFile(fileName, path, file.getInputStream());
            }
            return getFileAccessUrl(path + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public String upload(String name, String path, FileInputStream inputStream) {
        try {
            uploadFile(name, path, inputStream);
            return getFileAccessUrl(path + name);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * Exists boolean.
     * 判断文件是否存在
     *
     * @param filePath the file path
     * @return the boolean
     */
    public abstract Boolean exists(String filePath);

    /**
     * Upload file.
     * 上传文件
     *
     * @param name        the name
     * @param path        the path
     * @param inputStream the input stream
     */
    public abstract void uploadFile(String name, String path, InputStream inputStream) throws Exception;

    /**
     * Gets file access url.
     * 获得文件访问路径（url）
     *
     * @param path the path
     * @return the file access url
     */
    public abstract String getFileAccessUrl(String path);
}
